//
//  QWRoundCornerButton.m
//  OntheRoadV4
//
//  Created by hz on 11/21/13.
//  Copyright (c) 2013 EricHuang. All rights reserved.
//

#import "QWRoundCornerButton.h"

@implementation QWRoundCornerButton

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

- (void)setSelected:(BOOL)selected
{
    [super setSelected:selected];
    
    if (self.highlightedFillColor) {
        [self setNeedsDisplay];
    }
}

- (void)setHighlighted:(BOOL)highlighted
{
    [super setHighlighted:highlighted];
    
    if (self.highlightedFillColor) {
        [self setNeedsDisplay];
    }
}

- (void)setEnabled:(BOOL)enabled
{
    [super setEnabled:enabled];
    
    if (self.disabeFillColor) {
        [self setNeedsDisplay];
    }
}

- (void)setRadius:(CGFloat)radius
{
    _radius = radius;
    
    [self setNeedsDisplay];
}

- (void)setBorderWidth:(CGFloat)borderWidth
{
    _borderWidth = borderWidth;
    
    [self setNeedsDisplay];
}

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
    CGContextRef context = UIGraphicsGetCurrentContext();
    if (_radius < __FLT_EPSILON__) {
        _radius = 2.0f;
    }
    
    if (_borderWidth < __FLT_EPSILON__) {
        _borderWidth = 2.0f;
    }

    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0.0f, 0.0f, self.bounds.size.width, self.bounds.size.height)
                                                    cornerRadius:_radius];
    CGContextSaveGState(context);
    [path setLineWidth:_borderWidth];
    [path addClip];
    UIColor *border;
    if (self.selected || self.highlighted) {
        border = self.highlightedBorderColor;
    } else if (!self.enabled) {
        border = self.disableBorderColor;
    } else {
        border = self.normalBorderColor;
    }
    
    UIColor *fillColor;
    if (self.selected || self.highlighted) {
        fillColor = self.highlightedFillColor;
    } else if (!self.enabled) {
        fillColor = self.disabeFillColor;
    } else {
        fillColor = self.normalFillColor;
    }
    
    if (fillColor == nil) {
        fillColor = [UIColor clearColor];
    }
    
    [fillColor setFill];
    [path fill];
    
    if (border) {
        [border setStroke];
        [path stroke];
    }
    
    CGContextRestoreGState(context);
}

@end
